﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Main
{
    /// <summary>
    /// 将所有子节点预制件配置，后续通过加载AB包还原
    /// </summary>
    public class RemotePrefabsConfig : MonoBehaviour
    {
        public bool isAutoLoad = true;           // 是否自动加载
        public float firstDelay = 0.1f;          // 首次加载延迟
        public float intervalDelay = 0.1f;       // 加载间隔延迟
        public List<RemotePrefabItem> remotePrefabsConfigs = new List<RemotePrefabItem>();
        private List<AsyncOperationHandle> handles = new List<AsyncOperationHandle>();
        private IEnumerator Start()
        {
            yield return null;
            if (isAutoLoad)
            {
                yield return new WaitForSecondsRealtime(firstDelay);
                // 根据相机排列优先级
                Transform camera = Camera.main.transform;
                if (camera)
                {
                    remotePrefabsConfigs.Sort((item1, item2) =>
                    {
                        return (int)((item1.position - camera.position).sqrMagnitude - (item2.position - camera.position).sqrMagnitude);
                    });
                }
                for (int i = 0; i < remotePrefabsConfigs.Count; i++)
                {
                    RemotePrefabItem item = remotePrefabsConfigs[i];
                    var handle = Addressables.InstantiateAsync(item.assetPath, transform);
                    yield return handle;
                    handles.Add(handle);
                    RevertPrefab(item, handle.Result);
                    yield return new WaitForSecondsRealtime(intervalDelay);
                }
            }
        }
        private void OnDestroy()
        {
            foreach (var handle in handles)
            {
                Addressables.Release(handle);
            }
            handles.Clear();
        }
        private void RevertPrefab(RemotePrefabItem item, GameObject child)
        {
            child.name = item.name;
            child.isStatic = item.isStatic;
            child.tag = item.tag;
            child.layer = item.layer;
            child.transform.position = item.position;
            child.transform.rotation = item.rotation;
            child.transform.localScale = item.scale;
        }
    }
    [Serializable]
    public struct RemotePrefabItem
    {
        public string assetPath;
#if UNITY_EDITOR
        public string assetGUID;
#endif
        public string name;
        public bool isStatic;
        public string tag;
        public int layer;
        public Vector3 position;
        public Quaternion rotation;
        public Vector3 scale;
    }
}